package edu.ccut.osgi.test;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestResult;
import junit.framework.TestSuite;

import org.osgi.framework.BundleContext;

/**
 * OSGi Test Suite.
 * Allow the injection of the bundle context.
 */
public class OSGiTestSuite extends TestSuite {

    protected BundleContext context;

    public OSGiTestSuite(Class<Test> clazz, BundleContext bc) {
        super(clazz);
        context = bc;
    }

    public OSGiTestSuite(BundleContext bc) {
        super();
        context = bc;
    }

    public OSGiTestSuite(String name, BundleContext bc) {
        super(name);
        context = bc;
    }

    public OSGiTestSuite(Class<Test> clazz, String name, BundleContext bc) {
        super(clazz, name);
        context = bc;
   }

    public void setBundleContext(BundleContext bc) {
        context = bc;
    }

    /**
     * Adds the tests from the given class to the suite
     */
	@SuppressWarnings("unchecked")
	public void addTestSuite(Class testClass) {
        if (OSGiTestCase.class.isAssignableFrom(testClass)) {
            addTest(new OSGiTestSuite(testClass, context));
        } else if (TestCase.class.isAssignableFrom(testClass)) {
            addTest(new TestSuite(testClass));
        } else {
            System.out.println("Error : the " + testClass + " is not a valid test class");
        }
    }

    public void runTest(Test test, TestResult result) {
        if (test instanceof OSGiTestSuite) {
            ((OSGiTestSuite) test).context = context;
            test.run(result);
        } else if (test instanceof OSGiTestCase) {
            ((OSGiTestCase) test).context = context;
            test.run(result);
        } else {
            test.run(result);
        }
    }
}
